package com.ray.export.excel.content;

import com.ray.export.excel.ColumsBoolean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author bo shen
 * @Description: 数据校验
 * @Class: DataVerificationUtil
 * @Package com.ray.file.excel.content
 * @date 2019/11/28 14:42
 * @company <p>杭州传化陆鲸科技有限公司</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
public class DataVerificationUtil {

    private static Map<Class<?>, DataValid> valids = new HashMap<Class<?>, DataValid>();

    static {
        addDataValid(List.class,new ListValid());
        addDataValid(Map.class,new MapValid());
        addDataValid(Object.class,new ObjectValid());
    }

    /**
     * 添加一个执行器 如果key相同会替换原来的执行器
     *
     * @param clazz
     * @param valid
     */
    public static void addDataValid(Class<?> clazz, DataValid valid) {
        Assert.notNull(clazz, "参数[clazz]不能为空");
        Assert.notNull(valid, "参数[valid]不能为空");
        if (log.isDebugEnabled()) {
            log.debug("执行者{},{}被添加", clazz, valid.getClass().getName());
        }
        valids.put(clazz, valid);
    }



    /**
     * 获取实际的执行者
     * @param clazz
     * @return
     */
    public static DataValid getDataValidform(Class<?> clazz) {
        DataValid dataValid = valids.get(getClassType(clazz));
        if(ObjectUtils.isEmpty(dataValid)){
            log.info("参数为[{}]的数据校验对象不存在",clazz.getName());
            throw new RuntimeException("数据转对象不存在");
        }
        return  dataValid;
    }

    private static Class<?> getClassType(Class<?> clazz) {
        if (Map.class.isAssignableFrom(clazz)) {
            return Map.class;
        } else if (List.class.isAssignableFrom(clazz)) {
            return Map.class;
        } else {
            return Object.class;
        }
    }

    public static String verification(Object data, Map<String, ColumsBoolean> rule) {
        return getDataValidform(data.getClass()).Valid(data,rule);
    }
}
